<?php


namespace app\crm\logic;


use app\crm\model\Business;
use app\crm\model\Customer;
use think\facade\Db;

class BusinessLogic extends AbstractLogic
{

    /**
     * 获取销售新增数据
     * @param $userId
     * @param array $request
     * @return array
     * @author Mr.Li
     * @create 2021-08-05 10:50
     */
    public function getNewSalesData($userId,array $request): array
    {
        $data = [
            'name'      => '新增商机',
            'num'       => 0,
            'desc'      => '新增商机成功率',
            'value'     => 0
        ];
        $sqlWhere = '';
        if($request['start_time'] && $request['end_time']){
            $sqlWhere = append_where_sql($sqlWhere,"  create_time BETWEEN " . $request['start_time'] . " AND " . $request['end_time']);
        }
        $dataAuthCustomerId = (new Customer())->getDataAuthCustomer($userId, 'business');
        if(in_array(-1,$dataAuthCustomerId)){
            return $data;
        }
        $sqlWhere = !in_array('all', $dataAuthCustomerId) ? append_where_sql($sqlWhere," customer_id IN (" . implode(',', $dataAuthCustomerId) . ")") : $sqlWhere;
        $sqlWhere && $sqlWhere = ' where'.$sqlWhere;
        try {
            $sql = "select count(1) new_quantity,sum( CASE WHEN is_audit = 1 THEN 1 ELSE 0  END ) AS total_deal FROM shrimp_crm_business".$sqlWhere;
            $data = Db::query($sql);
            $data = array_map('intval',$data[0]);
            $data['new_conversion_rate'] = 0;
            $data['new_quantity'] && $data['new_conversion_rate'] = round($data['total_deal'] / $data['new_quantity'],4) * 100 .'%';
            unset($data['total_deal']);
            $data = [
                'name'      => '新增商机',
                'num'       => $data['new_quantity'],
                'desc'      => '新增商机成功率',
                'value'     => $data['new_conversion_rate']
            ];

        } catch (\Exception $e) {
        }
        return $data;
    }


    /**
     * 获取汇总数据
     * @param $userId
     * @param array $request
     * @return array
     * @author Mr.Li
     * @create 2021-08-06 14:23
     */
    public function getSummaryData($userId,array $request): array
    {
        $data = [
            [
                'name'        => '总计',
                'value'       => 0,
            ],
            [
                'name'        => '待处理',
                'value'       =>0,
            ],
            [
                'name'        => '处理中',
                'value'       => 0,
            ],
            [
                'name'        => '已完成',
                'value'       => 0,
            ],
        ];
        $dataAuthCustomerId = (new Customer())->getDataAuthCustomer($userId, 'business');
        if(in_array(-1,$dataAuthCustomerId)){
            return $data;
        }
        $where = [];
        !in_array('all', $dataAuthCustomerId) && array_push($where, ['customer_id', 'in', $dataAuthCustomerId]);
        $status = [0 => 'total_quantity',1 => 'total_pending_quantity',2 => 'total_processing_quantity',3 => 'total_completed_quantity'];
        // 状态搜索 0 :全部  1：待处理 2：处理中 3：成功 4：失败
        $statusNameArr = ['1' => '0', '2' => [4, 5, 6]];
        $auditNameArr  = ['3' => '1', '4' => '2'];
        try {
            foreach($status as $stat => $value){
                $searchWhere = $where;
                if (array_key_exists($stat, $statusNameArr)) {
                    array_push($searchWhere, ['status_id', 'in', $statusNameArr[$stat]]);
                } else if(array_key_exists($stat, $auditNameArr)) {
                    array_push($searchWhere, ['is_audit', '=', $auditNameArr[$stat]]);
                    array_push($searchWhere, ['status_id', '=', 7]);
                }
                $data[$value] = Db::name('crm_business')
                    ->where($searchWhere)->count();
                $searchWhere = [];
            }
            $data = [
                [
                    'name'      => '总计',
                    'value'       => $data['total_quantity'],
                ],
                [
                    'name'      => '待处理',
                    'value'       => $data['total_pending_quantity'],
                ],
                [
                    'name'      => '处理中',
                    'value'       => $data['total_processing_quantity'],
                ],
                [
                    'name'      => '已完成',
                    'value'       => $data['total_completed_quantity'],
                ],
            ];


        } catch (\Exception $e) {
        }
        return $data;

    }


    /**
     * 获取消息的条件
     * @author Mr.Li
     * @create 2021-08-10 16:20
     */
    protected function getMessageWhere($request)
    {
        $map = [];
        if(isset($request['is_today_allocate']) && $request['is_today_allocate'] ){//今日分配
            array_push($map,['b.create_time','>=',strtotime(date('Y-m-d') .' 00:00:00')]);
            array_push($map,['b.create_time','<=',strtotime(date('Y-m-d') .' 23:59:59')]);
        }
        isset($request['overtime'])  && (is_numeric($request['overtime']) ? array_push($map, ['b.last_time', '>=', $request['overtime'] * 86400]) :array_push($map, ['b.last_time', '=', -1])) ;
        return $map;
    }


    /**
     * 今日分配的商机数量
     * @param $userId
     * @param array $request
     * @return array
     * @author Mr.Li
     * @create 2021-08-09 14:55
     */
    public function getMessageNum($userId,array $request): int
    {
        $count = 0;
        $map = $this->getMessageWhere($request);
        try {
            // 获取客户数据权限 的客户ID
            $dataAuthCustomerId = (new Customer())->getDataAuthCustomer($userId, 'business');
            !in_array('all', $dataAuthCustomerId) && array_push($map, ['b.customer_id', 'in', $dataAuthCustomerId]);
            $count = Business::alias('b')->where($map)->count();

        }catch (\Exception $e) {
        }
        return $count;
    }

    /**
     * 获取消息列表
     * @param $userId
     * @param array $request
     * @return array
     * @author Mr.Li
     * @create 2021-08-09 15:40
     */
    public function getMessageList($userId,array $request): array
    {
        $data['dataCount'] = 0;
        $data['list'] = [];
        $map = $this->getMessageWhere($request);
        $dataAuthCustomerId = (new Customer())->getDataAuthCustomer($userId, 'business');
        !in_array('all', $dataAuthCustomerId) && array_push($map, ['b.customer_id', 'in', $dataAuthCustomerId]);

        $sqlQuery = Business::alias('b')
            ->join('crm_customer c', 'b.customer_id = c.customer_id', 'LEFT')
            ->where($map);
        $data['dataCount'] = $sqlQuery->count();

        $field = 'b.business_id, b.name, b.customer_id, b.create_user_id, b.owner_user_id, '.
            'b.trans_user_id, b.create_time, b.update_time, b.last_time, '.
            'b.status_id, b.is_audit, c.name as customer_name';
        $list  =$sqlQuery->field($field)
            ->order('b.business_id DESC')
            ->when(!(isset($request['no_page']) && $request['no_page']) ,function($query) use ($request){
                $query->limit(($request['page'] - 1) * $request['limit'], $request['limit']);
            })
            // ->limit(($request['page'] - 1) * $request['limit'], $request['limit'])
            ->select()->toArray();

        if ($list) {
            $ownerUserId  = array_column($list, 'owner_user_id');
            $createUserId = array_column($list, 'create_user_id');
            $transUserId  = array_column($list, 'trans_user_id');
            $userIdArr    = array_unique(array_merge($ownerUserId, $createUserId, $transUserId));
            $adminWhere   = [
                ['id', 'in', $userIdArr]
            ];
            $adminUser = Db::name('admin_user')->where($adminWhere)->column('realname', 'id');
            foreach ($list as $key => $val) {
                $list[$key]['last_time']   = $val['last_time'] ? date('Y-m-d H:i:s', $val['last_time']) : '';
                $list[$key]['create_user_name'] = $adminUser[$val['create_user_id']] ?? '';
                $list[$key]['owner_user_name']  = $adminUser[$val['owner_user_id']] ?? '';
                $list[$key]['trans_user_name']  = $adminUser[$val['trans_user_id']] ?? '';

                // 状态
                $statusName = '未知状态';
                if (!$val['status_id']) {
                    $statusName = '待处理';
                } else if (in_array($val['status_id'], [4, 5, 6])) {
                    $statusName = '处理中';
                } else if($val['status_id'] == 7) {
                    $statusName = $val['is_audit'] == 1 ? '成功' : '失败';
                }
                $list[$key]['status_name'] = $statusName;
            }
            $data['list'] = $list;
        }
        $permission = get_user_permission_menu($userId,'business_list_tag');
        $data['menu_list'] = $permission ? $permission : [];
        return $data;

    }


}
